<%--
  Created by IntelliJ IDEA.
  User: W
  Date: 2022/1/1
  Time: 22:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
%>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>双人五子棋</title>
        <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.min.js"></script>
        <script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
        <link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.css" rel="stylesheet">
        <style type="text/css">
            canvas {
                display: block;
                margin: 50px auto;
                background-color: sandybrown;
                /*box-shadow: -2px -2px 2px #F3F2F2, 5px 5px 5px #6F6767;*/
            }
        </style>
        <script type="text/javascript">
            let isClicked = false;
            let http_url = "<%=basePath%>/server/${clientID}";
            let socket_url = http_url.replace('http', 'ws');
            let socket;
            let commandID = 0;
            let isGaming = false;
            let isHost = false;
            let isBlack = true;
            let chess = undefined;
            let context = undefined;
            let last_x = -1;
            let last_y = -1;
        </script>
        <script type="text/javascript">
            function drawChessBoard() {
                $('#board')[0].height = $('#board')[0].height;
                for (var i = 0; i < 15; i++) {
                    context.strokeStyle = "#D6D1D1";
                    context.moveTo(15 + i * 30, 15);//垂直方向画15根线，相距30px;
                    context.lineTo(15 + i * 30, 435);
                    context.stroke();
                    context.moveTo(15, 15 + i * 30);//水平方向画15根线，相距30px;棋盘为14*14；
                    context.lineTo(435, 15 + i * 30);
                    context.stroke();
                }
            }
            function oneStep(i, j, k) {
                context.beginPath();
                context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);//绘制棋子
                var g = context.createRadialGradient(15 + i * 30, 15 + j * 30, 13, 15 + i * 30, 15 + j * 30, 0);//设置渐变
                if (k) {    //k=true是黑棋，否则是白棋
                    g.addColorStop(0, '#0A0A0A');//黑棋
                    g.addColorStop(1, '#636766');
                } else {
                    g.addColorStop(0, '#D1D1D1');//白棋
                    g.addColorStop(1, '#F9F9F9');
                }
                context.fillStyle = g;
                context.fill();
                context.closePath();
            }
            function drawSquare(i, j, color) {
                if (i < 0 || i > 14 || j < 0 || j > 14) {
                    return false;
                }
                context.strokeStyle = color;
                context.lineWidth = 2;
                context.beginPath();

                context.moveTo(i*30, j*30);
                context.lineTo(i*30+5, j*30);
                context.moveTo(i*30, j*30);
                context.lineTo(i*30, j*30+5);

                context.moveTo(i*30+30, j*30);
                context.lineTo(i*30+30-5, j*30);
                context.moveTo(i*30+30, j*30);
                context.lineTo(i*30+30, j*30+5);

                context.moveTo(i*30, j*30+30);
                context.lineTo(i*30+5, j*30+30);
                context.moveTo(i*30, j*30+30);
                context.lineTo(i*30, j*30+30-5);

                context.moveTo(i*30+30, j*30+30);
                context.lineTo(i*30+30-5, j*30+30);
                context.moveTo(i*30+30, j*30+30);
                context.lineTo(i*30+30, j*30+30-5);

                context.stroke();
            }
            $(function () {
                notConnectStatus();
                //----------------------------------------------------
                chess = document.getElementById("board");
                context = chess.getContext('2d');
                drawChessBoard();//绘制棋盘
                $(chess).click(function (e) {
                    if (!isClicked) {
                        return;
                    }
                    var x = e.offsetX;//相对于棋盘左上角的x坐标
                    var y = e.offsetY;//相对于棋盘左上角的y坐标
                    var i = Math.floor(x / 30);
                    var j = Math.floor(y / 30);
                    dropChess(i, j, isBlack);
                });
                openSocket();
            });
        </script>
        <script type="text/javascript">
            function notConnectStatus() {
                isClicked = false;
                isGaming = false;
                $("#info").text('');
                $('#connect').text('连接到服务器');
                $('#connect').attr('disabled', false);
                $('#match').attr('disabled', true);
                $('#cede').attr('disabled', true);
            }
            function connectedStatus() {
                isClicked = false;
                isGaming = false;
                $("#info").text('');
                $('#connect').text('已连接');
                $('#connect').attr('disabled', true);
                $('#match').attr('disabled', false);
                $('#cede').attr('disabled', true);
            }
            function matchingStatus() {
                isClicked = false;
                isGaming = false;
                $("#info").text('');
                $('#connect').text('已连接');
                $('#connect').attr('disabled', true);
                $('#match').attr('disabled', true);
                $('#match').text('正在匹配');
                $('#cede').attr('disabled', true);
            }
            function matchedStatus() {
                isClicked = true;
                isGaming = true;
                $("#info").text('');
                $('#connect').text('已连接');
                $('#connect').attr('disabled', true);
                $('#match').attr('disabled', true);
                $('#cede').attr('disabled', false);
            }
        </script>
        <script type="text/javascript">
            function openSocket() {
                socket = new WebSocket(socket_url);
                socket.onopen = function () {};
                socket.onmessage = function (msg) {
                    var data = JSON.parse(msg.data);
                    if (data['type'] === 'reply') {
                        switch (data['name']) {
                            case 'connect':
                                connect();
                                break;
                            case 'match':
                                match(data);
                                break;
                            case 'start':
                                start(data);
                                break;
                            case 'drop':
                                drop(data);
                                break;
                            case 'end':
                                end(data);
                                break;
                        }
                    } else if (data['type'] === 'info') {
                        if (data['name'] === 'error') {
                            alert(data['info']);
                            location.reload();
                        }
                    }
                }
            }
            function matchPartner() {
                if (socket === undefined) {
                    alert("未连接到服务器");
                    return false;
                }
                var data = {
                    commandID: ++ commandID,
                    name: 'match',
                    clientID: '${clientID}'
                };
                socket.send(JSON.stringify(data));
            }
            function dropChess(i, j, isBlack) {
                var color = 2;
                if (isBlack) {
                    color = 1;
                }
                var data = {
                    commandID: ++ commandID,
                    name: 'drop',
                    clientID: '${clientID}',
                    params: {'x': i, 'y': j, 'color': color},
                };
                socket.send(JSON.stringify(data));
            }
            function cede() {
                if (socket === undefined) {
                    alert("未连接到服务器");
                    return false;
                }
                var data = {
                    commandID: ++ commandID,
                    name: 'cede',
                    params: {'info': '对方要求和棋'},
                    clientID: '${clientID}',
                };
                socket.send(JSON.stringify(data));
            }

            function connect() {
                console.log('成功连接到服务器!');
                connectedStatus();
            }
            function match(data) {
                if (data['status'] === false) {
                    matchingStatus();
                } else {
                    alert('匹配成功');
                    matchedStatus();
                    if (data['role'] === "host") {
                        isHost = true;
                        isBlack = true;
                        var command = {
                            commandID: ++ commandID,
                            name: 'start',
                            clientID: '${clientID}',
                            params: {'color': 2, 'isBlack': false},
                        };
                        socket.send(JSON.stringify(command));
                        $('#info').text('本轮执黑棋');
                    }
                }
            }
            function start(data) {
                isGaming = true;
                isBlack = Boolean(data['isBlack']);
                matchedStatus();
                if (isBlack) {
                    $('#info').text('本轮执黑棋');
                } else {
                    $('#info').text('本轮执白棋');
                }
            }
            function drop(data) {
                if (data['status']) {
                    var x = Number(data['x']);
                    var y = Number(data['y']);
                    var isBlack = Boolean(data['isBlack']);
                    drawSquare(last_x, last_y, 'sandybrown');
                    last_x = x;
                    last_y = y;
                    oneStep(x, y, isBlack);
                    var color = isBlack ? 'black' : 'white';
                    drawSquare(x, y, color);
                } else {
                    alert(data['info']);
                }
            }
            function end(data) {
                alert(data['info']);
                drawChessBoard();
                if (isHost) {
                    var color = isBlack ? 1 : 2;
                    var command = {
                        commandID: ++ commandID,
                        name: 'start',
                        clientID: '${clientID}',
                        params: {'color': color, 'isBlack': isBlack},
                    };
                    socket.send(JSON.stringify(command));
                    isBlack = !isBlack;
                    if (isBlack) {
                        $('#info').text('本轮执黑棋');
                    } else {
                        $('#info').text('本轮执白棋');
                    }
                }
            }
        </script>
        <script type="text/javascript">
            function connect_click() {
                openSocket();
            }
            function match_click() {
                matchPartner();
            }
            function undo_click() {

            }
            function cede_click() {
                cede();
            }
        </script>
    </head>
    <body>
        <div class="container" style="height: 100vh;">
            <div style="float:left">
                <canvas id="board" width="450px" height="450px"></canvas>
            </div>
            <div style="float:left; width: 250px; height: 450px; margin-top: 75px">
                <table class="table table-hover">
                    <tr>
                        <td style="text-align: center">
                            <label id="info">本轮执黑棋</label>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <button id="connect" class="btn" type="button" onclick="connect_click();">连接到服务器</button>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <button id="match" class="btn" type="button" onclick="match_click();">匹配对手</button>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <button id="cede" class="btn" type="button" onclick="cede_click();">认输</button>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </body>
</html>
